<script setup lang="tsx">
import { reactive, ref, watch } from 'vue';
import { ElTree } from 'element-plus';
import { delRoyiUser, downRoyiUser, getRoyiDeptTree, getRoyiListUser, resetUserPwd } from '@/service/api';
import { parseTime } from '@/utils';
import Modal from '@/components/common/modal.vue';
import Search from './modules/search.vue';
import AddUserForm from './modules/add-user-form.vue';
import TableOperation from './modules/table-operation.vue';
import ImportUser from './modules/import-user.vue';

const deptName = ref<any>(null);
const deptOptions = ref([]);
const defaultProps = {
  children: 'children',
  label: 'label'
};
const treeRef: any = ref(null);
const params = reactive({
  userName: null,
  nickName: null,
  status: null,
  deptId: null,
  time: null
});
// 筛选节点
function filterNode(value: any, data: any) {
  if (!value) return true;
  return data.label.includes(value);
}

function handleNodeClick(node: any) {
  params.deptId = node.id;
  getData();
}

function getTreeData() {
  getRoyiDeptTree().then(({ data, error }) => {
    if (!error) {
      deptOptions.value = data;
    }
  });
}

getTreeData();

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: (total: number) => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current: number, size: number) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});
const tableData = ref([]);
const loading = ref(false);
const columnChecks = ref<any[]>([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 80,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'userName',
    dataIndex: 'userName',
    title: '用户名称',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'nickName',
    dataIndex: 'nickName',
    title: '用户昵称',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'dept.deptName',
    dataIndex: 'dept.deptName',
    // width: '200',
    title: '部门',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return record.dept?.deptName;
    }
  },
  {
    key: 'workNo',
    dataIndex: 'workNo',
    title: '工号',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',

    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.status === null) {
        return null;
      }

      const label = record.status == 0 ? '正常' : '停用';

      return <span class={record.status == 0 ? 'color-green' : 'color-red'}>{label}</span>;
    }
  },
  {
    key: 'loginIp',
    dataIndex: 'loginIp',
    title: '登陆IP',
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: ' loginDate',
    dataIndex: ' loginDate',
    title: '最后登录时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.loginDate == null) {
        return null;
      }

      return parseTime(record.loginDate);
    }
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '创建时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.createTime == null) {
        return null;
      }

      return parseTime(record.createTime);
    }
  },
  {
    key: 'cz',
    dataIndex: 'cz',
    title: '操作',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 200,
    fixed: 'right',
    customRender: ({ record }) => {
      if (record.userId !== 1) {
        return (
          <TableOperation
            onOperationClick={type => {
              if (type === 'edit') {
                handleAddUser('edit', record);
              }
              if (type === 'delete') {
                delUser(record);
              }
              if (type === 'resetPassword') {
                handleChangeUserMsg(record);
              }
            }}
          ></TableOperation>
        );
      }
    }
  }
]);

const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      // 'background-color': record.userId === currentRowId.value ? 'rgba(86, 205, 243, 0.3)' : ''
      background: record.userId === currentRowId.value ? '#BAEAFA' : ''
    },
    class: record.userId === currentRowId.value ? 'jl-table-row-selected' : '',
    onClick: () => {
      currentRowId.value = record.userId;
    }
  };
};

const selectedRowKeys = ref([]);

function tableSelectChange(val) {
  selectedRowKeys.value = val;
}

function getData() {
  const { userName, nickName, status, deptId, time } = params;
  const searchData: any = {
    userName,
    nickName,
    status,
    deptId,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  };
  if (time?.[0]) {
    searchData['params[beginTime]'] = time[0];
    searchData['params[endTime]'] = time[1];
  }
  getRoyiListUser(searchData).then( res => {
      let data = res.otherData
      data.rows.forEach((item, index) => {
        item.index = index + 1;
      });
      pagination.total = data?.total || 0;
      tableData.value = data.rows;
      // if (!error) {
      //   data.rows.forEach((item, index) => {
      //     item.index = index + 1;
      //   });
      //   pagination.total = data?.total || 0;
      //   tableData.value = data.rows;
      // }
    })
    .finally(() => (loading.value = false));
}

getData();

function search() {
  pagination.current = 1;
  getData();
}

function reset() {
  params.deptId = null;
  search();
}

watch(
  () => deptName.value,
  val => {
    treeRef.value.filter(val);
  }
);

function handleExport() {
  const { userName, phonenumber, status, deptId, time } = params;
  const searchData: any = {
    userName,
    phonenumber,
    status,
    deptId,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  };
  if (time?.[0]) {
    searchData['params[beginTime]'] = time[0];
    searchData['params[endTime]'] = time[1];
  }
  downRoyiUser(searchData);
}

const operateType = ref<AntDesign.TableOperateType>('add');
const currentRowData = ref(null);
// 新增用户
const addUserVisible = ref(false);
const addUserFormRef = ref<any>(null);
function handleAddUser(type: AntDesign.TableOperateType, row = null) {
  console.log(row);

  currentRowData.value = row;
  operateType.value = type;
  addUserVisible.value = true;
}

function addUserSuccess() {
  addUserVisible.value = false;
  reset();
}

function handleClose() {
  addUserVisible.value = false;
}

function handleAddUserOk() {
  addUserFormRef.value.sumbitForm();
}

function delUser(row: any) {
  let delIds: string;
  if (row) {
    delIds = row.userId;
  } else {
    delIds = selectedRowKeys.value.join();
  }
  window.$modal?.confirm({
    title: `是否确认删除用户编号为"${delIds}"的数据项?`,
    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          window.$message?.success('删除成功!');
          reset();
        } else {
          window.$message?.error('删除失败!');
        }
      });
    },
    onCancel: () => {}
  });
}

// 导入用户
const importUserVisible = ref(false);
const importUserRef: any = ref<any>(false);
function handleInportUser() {
  importUserVisible.value = true;
}
function handleImportUserOk() {
  importUserRef.value.uploadData();
}

function handleImportUserClose() {
  importUserVisible.value = false;
}

function handleInportUserSuccess() {
  handleImportUserClose();
  reset();
}

const changeUserMsgVisible = ref(false);
const changeUserMsg = ref({
  userName: '',
  passwrod: '',
  userId: null
});

function handleChangeUserMsg(val) {
  changeUserMsgVisible.value = true;
  changeUserMsg.value.userName = val.userName;
  changeUserMsg.value.userId = val.userId;
}

function handlechangeUserMsgOk() {
  if (/<|>|"|'|\||\\/.test(changeUserMsg.value.passwrod)) {
    window.$message?.error('密码格式不匹配');
  }
  resetUserPwd(changeUserMsg.value.userId, changeUserMsg.value.passwrod).then(({ data, error }) => {
    if (!error) {
      window.$message?.success(`修改成功,新密码为:${changeUserMsg.value.passwrod}`);
      changeUserMsg.value = {
        userName: '',
        passwrod: '',
        userId: null
      };
      changeUserMsgVisible.value = false;
    }
  });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <ARow :gutter="15" class="h-full">
      <ACol :span="4" class="dept h-full">
        <div class="title">
          <span class="text">部门</span>
        </div>
        <div class="head-container">
          <AInput v-model:value="deptName" placeholder="请输入部门名称" />
        </div>
        <div class="head-tree">
          <ElTree
            ref="treeRef"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            node-key="id"
            default-expand-all
            highlight-current
            empty-text="暂无部门数据"
            @node-click="handleNodeClick"
          />
        </div>
      </ACol>
      <ACol :span="20" class="h-full flex-col-stretch gap-16px overflow-hidden">
        <!-- <div class="user-page min-h-500px  lt-sm:overflow-auto"> -->
        <Search v-model:model="params" class="search-box" @reset="reset" @search="search" />
        <ACard
          :bordered="false"
          :body-style="{ flex: 1, overflow: 'hidden' }"
          class="table-card h-full flex-col-stretch sm:flex-1-hidden card-wrapper"
        >
          <template #title>
            <AButton type="primary" ghost class="mini-btn mr-8px" @click="handleAddUser('add')">
              <template #icon>
                <icon-ic-round-add class="align-sub text-icon" />
              </template>
              <span class="ml-3px">新增</span>
            </AButton>
            <AButton
              danger
              ghost
              class="mini-btn mr-8px"
              :disabled="selectedRowKeys.length == 0"
              @click="delUser(null)"
            >
              <template #icon>
                <icon-ic-round-delete class="align-sub text-icon" />
              </template>
              <span class="ml-3px">删除</span>
            </AButton>
            <AButton ghost type="primary" class="mini-btn mr-8px" @click="handleInportUser">
              <template #icon>
                <icon-ic-round-upload class="align-sub text-icon" />
              </template>
              <span class="ml-3px">导入</span>
            </AButton>
            <AButton ghost type="primary" class="mini-btn mr-8px" @click="handleExport">
              <template #icon>
                <icon-ic-round-download class="align-sub text-icon" />
              </template>
              <span class="ml-3px">导出</span>
            </AButton>
          </template>
          <template #extra>
            <TableColumnSetting v-model:columns="columnChecks" />
          </template>
          <STable
            :columns="columnChecks"
            :data-source="tableData"
            bordered
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: tableSelectChange }"
            size="small"
            :loading="loading"
            row-key="userId"
            :pagination="pagination"
            :custom-row="customRow"
            :scroll="{ x: 1600, y: 'auto' }"
            class="h-full"
            :row-height="23"
          />
        </ACard>
        <!-- </div> -->
      </ACol>
    </ARow>

    <!-- 新增修改用户 -->
    <Modal
      v-model:visible="addUserVisible"
      :title="`${operateType == 'add' ? '新增' : '修改'}用户`"
      height="70vh"
      width="800px"
      :destroy-on-close="true"
      @ok="handleAddUserOk"
    >
      <AddUserForm
        ref="addUserFormRef"
        :operate-type="operateType"
        :row-data="currentRowData"
        :dept-options="deptOptions"
        @success="addUserSuccess"
      ></AddUserForm>
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" @click="handleAddUserOk()">确定</AButton>
          <AButton @click="handleClose">取消</AButton>
        </div>
      </template>
    </Modal>

    <!-- 导入用户 -->
    <Modal
      v-model:visible="importUserVisible"
      title="导入用户"
      height="450px"
      width="590px"
      :destroy-on-close="true"
      @ok="handleImportUserOk"
    >
      <ImportUser ref="importUserRef" @success="handleInportUserSuccess" />
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" @click="handleImportUserOk()">确定</AButton>
          <AButton @click="handleImportUserClose">取消</AButton>
        </div>
      </template>
    </Modal>
    <!-- 重置密码 -->
    <Modal
      v-model:visible="changeUserMsgVisible"
      :title="`重置${changeUserMsg.userName}的密码`"
      height="180px"
      width="590px"
      :destroy-on-close="true"
      @reset="changeUserMsg.passwrod = ''"
      @ok="handlechangeUserMsgOk"
    >
      <div>
        <AInputPassword v-model:value="changeUserMsg.passwrod" placeholder="请输入新密码" autocomplete="off" />
      </div>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.dept {
  padding: 8px;
  background: #fff;
  box-shadow: 2px 5px 8px 0 #eee;
  .title {
    text-align: center;
    color: #646cff;
    font-size: 18px;
    font-weight: bold;
    padding: 5px;
    .text {
      border-bottom: 2px solid #646cff;
      padding: 0 8px;
    }
  }
  .head-tree {
    height: calc(100% - 75px);
    overflow: auto;
  }
}
</style>
